<script setup lang="ts">
  import { Plus, Delete, Search, Refresh } from '@element-plus/icons-vue';
  import { getDatalist, deleteTableList, saveData, getMultipleLanguages } from '@/api/sourceData';
  import { GetMenu } from '@/api/publicApi';
  // import { da } from 'element-plus/es/locale';
  import { ElLoading } from 'element-plus';
  const height = ref<string>('calc(100vh - 168px)');
  const TablesData = ref<any>();
  interface Emits {
    (e: 'update:value', val: Array<Namespace.tableData>): void;
  }
  const emit = defineEmits<Emits>();
  const languageType = ref<Array<Namespace.menuType>>();
  interface state {
    tableData: Array<Namespace.tableData>;
    total: number;
    pageSize: number;
    currentPage: number;
    parameterKey: string;
    filterTableData: any[];
    MultiSelectData: Array<Namespace.tableData>;
    queryData: Array<Namespace.tableData>;
    IconsName: number;
    IconAdd: boolean;
    MultipleLanguages: boolean;
  }
  const props = defineProps({
    id: {
      type: String,
      default: '',
    },
    tableData: {
      type: Array<Namespace.tableData>,
      default: [],
    },
  });
  let languageTypeSelect = ref<string>('');
  const languageTypeSelectData = ref<any>([]);
  const state: state = reactive({
    tableData: [],
    total: 0,
    pageSize: 10,
    currentPage: 1,
    parameterKey: '',
    filterTableData: [],
    MultiSelectData: [],
    queryData: [],
    IconsName: 0,
    IconAdd: false,
    MultipleLanguages: false,
  });
  watch(
    () => props.tableData,
    (value: Array<Namespace.tableData>) => {
      state.tableData = value;
      state.queryData = value;
      state.total = value.length;
      state.tableData.forEach((item, index) => {
        item.index = index;
      });
      state.queryData.forEach((item, index) => {
        item.index = index;
      });
    },
    {
      deep: true,
      immediate: true,
    },
  );
  onMounted(async () => {
    const { data } = await GetMenu('language_type');
    languageType.value = data;
    languageTypeSelectData.value = data;
  });
  const handleSizeChange = (value: number) => {
    state.currentPage = 1;
    state.pageSize = value;
  };
  const handleCurrentChange = (value: number) => {
    state.currentPage = value;
  };
  const handleKey = async () => {
    if (state.parameterKey) {
      state.parameterKey = state.parameterKey.toLowerCase();
      state.tableData = state.queryData.filter((item) => {
        return item.parameterKey.includes(state.parameterKey);
      });
      state.total = state.tableData.length;
      state.currentPage = 1;
      state.pageSize = 10;
    } else {
      const { data } = await getDatalist(props.id);
      state.tableData = data;
      state.queryData = data;
      state.tableData.forEach((item, index) => {
        item.index = index;
      });
      state.queryData.forEach((item, index) => {
        item.index = index;
      });
    }
  };
  const handleRefresh = async () => {
    const { data, code } = await getDatalist(props.id);
    if (code == 0) {
      state.total = data.length;
      state.parameterKey = '';
      state.currentPage = 1;
      state.pageSize = 10;
      ElMessage.success('重置成功');
      state.tableData = data;
      state.queryData = data;
      state.tableData.forEach((item, index) => {
        item.index = index;
      });
      state.queryData.forEach((item, index) => {
        item.index = index;
      });
    }
  };
  const handleSelectionChange = async (value: Array<Namespace.tableData>) => {
    state.MultiSelectData = value;
  };
  const handleDlete = async () => {
    if (!state.MultiSelectData.length) {
      ElMessage.info('请选择需要删除的数据！');
    } else {
      const dataIds = state.MultiSelectData.map((item) => {
        return item.parameterId as number;
      });
      const { code } = await deleteTableList(dataIds);
      if (code == 0) {
        const dataMap = state.MultiSelectData.map((item) => {
          return item.index as number;
        });
        state.tableData = state.tableData.filter((item) => {
          return !dataMap.includes(item.index as number);
        });
        state.queryData = state.tableData;
        state.total = state.tableData.length;
        emit('update:value', state.tableData);
      }
    }
  };
  const handleinlineAdd = () => {
    state.tableData.unshift({
      edit: true,
      parameterKey: '', // 参数名
      parameterName: '', // 解释 / 标题名
      orderNum: null, // 顺序
      parameterKeyzu: 2,
      unitId: props.id as unknown as number,
      unitField1: '',
      unitField2: '',
      unitField3: '',
    });
    state.total = state.tableData.length;
    state.tableData.forEach((item, index) => {
      item.index = index;
    });
  };

  const handelEdit = (row) => {
    row.edit = !row.edit;
  };

  const handleSaveData = async () => {
    state.tableData.map((item) => {
      delete item.index;
      delete item.createDate;
      delete item.edit;
      return item;
    });
    let Json = JSON.stringify(state.tableData);
    const { code } = await saveData(Json);
    if (code == 0) {
      const { data } = await getDatalist(props.id);
      state.tableData = data;
      state.queryData = data;
      state.tableData.forEach((item, index) => {
        item.index = index;
      });
      state.queryData.forEach((item, index) => {
        item.index = index;
      });
      state.total = state.tableData.length;
      state.currentPage = 1;
      state.pageSize = 10;
    }
  };
  const handlIconAdd = async (value: number) => {
    state.IconsName = value;
    state.IconAdd = !state.IconAdd;
  };
  const handleCloseIcons = () => {
    state.IconAdd = !state.IconAdd;
  };
  const LoadMultipleLanguages = async () => {
    state.MultipleLanguages = !state.MultipleLanguages;
  };
  const handleCloseMultipleLanguages = () => {
    state.MultipleLanguages = !state.MultipleLanguages;
  };
  const LoadMultipleLanguagesCommit = async () => {
    console.log('languageTypeSelect', languageTypeSelect);
    if (!languageTypeSelect.value) {
      ElMessage.error('请先选择需要转换的语言!');
      return false;
    }
    const loading = ElLoading.service({
      lock: true,
      text: '获取中',
      background: 'rgba(0, 0, 0, 0.7)',
    });
    try {
      const { data } = await getMultipleLanguages(props.id, languageTypeSelect.value);
      console.log('data', data);
    } catch (error) {}
    loading.close();
  };
  const handleHTML = (value) => {
    state.tableData[state.IconsName].unitField3 = value;
    state.IconAdd = !state.IconAdd;
  };
</script>

<template>
  <div class="table_content">
    <div class="table_content_search">
      <div class="search">
        <ElInput
          v-model="state.parameterKey"
          placeholder="参数名回车后查询"
          style="height: 38px; width: 300px"
          @keyup.enter="handleKey"
        />
      </div>
      <div class="button">
        <ElButton type="primary" :icon="Search" @click="handleKey">查询</ElButton>
        <ElButton type="info" :icon="Refresh" @click="handleRefresh">重置</ElButton>
        <ElButton type="primary" :icon="Plus" @click="handleinlineAdd">新增</ElButton>
        <ElButton type="danger" :icon="Delete" @click="handleDlete">删除</ElButton>
        <ElButton type="primary" @click="handleSaveData">保存</ElButton>
        <ElButton type="primary" @click="LoadMultipleLanguages">加载多语言</ElButton>
      </div>
    </div>
    <div class="table_content_tables">
      <ElTable
        ref="TablesData"
        :data="
          state.tableData.slice(
            (state.currentPage - 1) * state.pageSize,
            state.currentPage * state.pageSize,
          )
        "
        style="width: 100%"
        :max-height="height"
        border
        table-layout="fixed"
        @selection-change="handleSelectionChange"
      >
        <ElTableColumn type="selection" width="55" />
        <ElTableColumn label="操作">
          <template #default="scope">
            <ElButton @click="handelEdit(scope.row)">编辑/取消</ElButton>
          </template>
        </ElTableColumn>
        <ElTableColumn label="顺序" prop="orderNum">
          <template #default="scope">
            <ElInput v-if="scope.row.edit" v-model.number="scope.row.orderNum" />
            <span v-else>{{ scope.row.orderNum }}</span>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="parameterKey" label="数据值">
          <template #default="scope">
            <ElInput v-if="scope.row.edit" v-model="scope.row.parameterKey" />
            <span v-else>{{ scope.row.parameterKey }}</span>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="parameterName" label="解释">
          <template #default="scope">
            <ElInput v-if="scope.row.edit" v-model="scope.row.parameterName" />
            <span v-else>{{ scope.row.parameterName }}</span>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="plurilingual" label="多语言配置">
          <template #default="scope">
            <ElSelect v-if="scope.row.edit" v-model="scope.row.plurilingual">
              <ElOption
                v-for="item in languageType"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </ElSelect>
            <span v-else>{{
              scope.row.plurilingual
                ? languageType?.filter((item) => scope.row.plurilingual == item.value)[0].name
                : ''
            }}</span>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="unitField1" label="标题">
          <template #default="scope">
            <ElInput v-if="scope.row.edit" v-model="scope.row.unitField1" />
            <span v-else>{{ scope.row.unitField1 }}</span>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="unitField2" label="时间">
          <template #default="scope">
            <ElInput v-if="scope.row.edit" v-model="scope.row.unitField2" />
            <span v-else>{{ scope.row.unitField2 }}</span>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="unitField3" label="图标">
          <template #default="scope">
            <ElInput
              v-if="scope.row.edit"
              v-model="scope.row.unitField3"
              @click="handlIconAdd(scope.$index)"
            />
            <span v-else v-html="scope.row.unitField3"></span>
          </template>
        </ElTableColumn>
      </ElTable>
      <div style="margin-top: 20px">
        <ElPagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="state.currentPage"
          :page-sizes="[1, 5, 10, 20]"
          background
          :page-size="state.pageSize"
          layout="prev, pager, next, sizes, jumper"
          :total="state.total"
        />
      </div>
      <ElDialog
        :model-value="state.IconAdd"
        title="设置图标"
        :before-close="handleCloseIcons"
        width="70%"
        lock-scroll
        align-center
        :destroy-on-close="true"
      >
        <ElementIcons @update:icons="handleHTML" />
      </ElDialog>
      <ElDialog
        :model-value="state.MultipleLanguages"
        title="加载多语言"
        :before-close="handleCloseMultipleLanguages"
        width="400px"
        lock-scroll
        align-center
        :destroy-on-close="true"
      >
        <ElSelect v-model="languageTypeSelect" style="width: 100%" filterable>
          <ElOption
            v-for="items in languageTypeSelectData"
            :key="items.value"
            :label="items.name"
            :value="items.value"
            :disabled="items.value == 'zh'"
          />
        </ElSelect>
        <template #footer>
          <ElButton type="primary" @click="LoadMultipleLanguagesCommit">提交</ElButton>
        </template>
      </ElDialog>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .table_content {
    &_search {
      display: flex;
      flex-direction: row;
      align-items: center;
      .button {
        margin-left: 50px;
        :deep(.el-button) {
          height: 38px;
        }
      }
    }
    &_tables {
      padding-top: 20px;
      :deep(th) {
        color: #000;
        background-color: rgba(9, 96, 189, 0.05);
        background-image: linear-gradient(rgba(9, 96, 189, 0.1), #fff);
      }
      :deep(.el-radio) {
        margin-right: 15px;
      }
      :deep(.el-radio:last-child) {
        margin-right: 0;
      }
      :deep(.el-radio--large) {
        height: 25px;
      }
    }
  }
</style>
